<template>
  <div class="projectList">
    <div class="main-table">
      <el-button-group>
        <el-button type="primary" icon="el-icon-caret-right" @click="catalogOperate('closeCatalog')">折叠所有节点</el-button>
        <el-button type="primary" icon="el-icon-caret-bottom" @click="catalogOperate('openCatalog')">展开所有节点</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="catalogOperate('refreshCatalog')">刷新</el-button>
      </el-button-group>
      <div class="main-table-div">
        <el-table
          ref="catalogTree"
          :data="config.mapSourceTreeData"
          style="width:100%"
          row-key="id"
          lazy
          border
          :load="load"
          :tree-props="{children:'children',hasChildren:'hasChildren'}"
        >
          <el-table-column
            prop="name"
            label="名称"
            width="300px"
            align="left"
            fixed="left"
          ></el-table-column>
          <el-table-column
            prop="url"
            align="center"
            label="数据地址"
          ></el-table-column>
          <el-table-column
            prop="servicetype"
            align="center"
            width="100px"
            label="数据类型"
          ></el-table-column>
          <el-table-column
            prop="isvisible"
            align="center"
            width="100px"
            label="是否可见"
          >
            <template slot-scope="scope">
              <template v-if="scope.row.type===1">
                <el-switch v-model="scope.row.isvisible===1"></el-switch>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="islabel"
            align="center"
            width="100px"
            label="是否注记"
          >
            <template slot-scope="scope">
              <template v-if="scope.row.type===1">
                <el-switch v-model="scope.row.islabel===1"></el-switch>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="operate"
            align="center"
            label="操作"
            width="280px"
          >
            <template slot-scope="scope">
              <template v-if="scope.row.type===0">
                <el-button type="text" icon="el-icon-plus" size="mini"
                           @click="catalogOperate('addService',scope.$index,scope.row)">添加服务
                </el-button>
              </template>
              <template v-if="scope.row.type===1">
                <el-button type="text" icon="el-icon-edit" size="mini"
                           @click="catalogOperate('edit',scope.$index,scope.row)">编辑
                </el-button>
                |
                <el-button type="text" icon="el-icon-delete" size="mini"
                           @click="catalogOperate('delete',scope.$index,scope.row)">删除
                </el-button>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="sort"
            align="center"
            label="排序"
            width="180px"
          >
            <template slot-scope="scope">
              <template v-if="scope.row.type===1">
                <el-button type="text" size="mini" @click="catalogOperate('orderToTop',scope.$index,scope.row)">置顶
                </el-button>
                |
                <el-button type="text" size="mini" @click="catalogOperate('orderUp',scope.$index,scope.row)">上移
                </el-button>
                |
                <el-button type="text" size="mini" @click="catalogOperate('orderDown',scope.$index,scope.row)">下移
                </el-button>
                |
                <el-button type="text" size="mini" @click="catalogOperate('orderToBottom',scope.$index,scope.row)">置底
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <component :is="dialogConfig.dialogComponent" :config="dialogConfig.config" :param="dialogConfig.param"
               :form="dialogConfig.form"></component>
  </div>
</template>

<script>
import * as gcf from '@/utils/Global/GlobalCommonFunction'
import bus from '@/utils/bus';
import {IsNotNullStr} from '@/utils/Global/GlobalCommonFunction'
import { listDict } from '@/api/system/dict/tbportalDict'
import { deleteMapSourceItem, listMapSource, sortMapSource } from '@/api/resource/mapSource'

export default {
  name: 'mapSource',
  data() {
    return {
      config: {
        mapSourceData: [],
        mapSourceTreeData: [],
        mapDataTypeData: [],
        serviceTypes: [],
        prjTypes: []
      },
      dialogConfig: {
        dialogComponent: undefined,
        config: {
          title: "",
          show: false,
          itemShow: {},
          innerHtml: "",
          okBtnText: ""
        },
        params: {},
        form: {}
      }
    }
  },
  beforeMount() {
    this.queryServiceType({
      "queryType": "byDictKey",
      "dictKey": "serviceType"
    });
    this.queryPrjType({
      "queryType": "byDictKey",
      "dictKey": "prjType"
    });
    this.queryMapSource({});
  },
  mounted() {
    bus.$on("refreshMapSource", msg => {
      let that = this;
      that.queryMapSource({});
    })
  },
  methods: {
    /**
     * 添加服务
     * @param parentId
     * @param parentName
     * @param children
     * @constructor
     */
    addMapService(parentId, parentName, children) {
      let that = this;
      that.dialogConfig.config = {
        title: "添加服务",
        show: true,
        itemShow: {
          isLabel: false
        },
        okBtnText: "添加",
      };
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editMapService.vue'], resolve);
      that.config.mapDataTypeData = [];
      that.formatParentNodeTreeData(that.config.mapDataTypeData, "", parentId, "", that.config.mapSourceTreeData);
      that.dialogConfig.param = {
        parentCatalogTreeData: that.config.mapDataTypeData,
        prjTypes: that.config.prjTypes,
        serviceTypes: that.config.serviceTypes
      };
      let sortid = children.length
      for (let i in children) {
        let sortIndex = children[i]['sortid']
        if (sortid <= sortIndex) {
          sortid = sortIndex
        }
      }
      that.dialogConfig.form = {
        operatetype: "insertService",
        parentCatalog: parentId,
        parentCatalogName: parentName,
        sortid: sortid
      }
    },
    /**
     * 操作按钮事件
     * @param operateType
     * @param index
     * @param row
     */
    catalogOperate(operateType, index, row) {
      let that = this;
      let items = [];
      switch (operateType) {
        case "closeCatalog"://关闭所有目录
          that.$nextTick(() => {
            that.setAllExpand(that.config.mapSourceTreeData, false);
          });
          break;
        case "openCatalog"://打开所有目录
          that.$nextTick(() => {
            that.setAllExpand(that.config.mapSourceTreeData, true);
          });
          break;
        case "refreshCatalog"://刷新目录
          that.queryMapSource({});
          break;
        case "addService"://添加服务节点
          that.addMapService(row.id, row.name,row.children);
          break;
        case "edit"://节点编辑
          that.editMapService(row);
          break;
        case "delete"://删除节点
          that.deleteServiceItem(row.id, row.name);
          break;
        case "orderToTop"://排序置顶
          items = [];
          items.push({
            "id": row.id,
            "sortid": 1
          });
          that.config.mapSourceData.forEach((ite,i)=>{
            if ((ite.pid == row.pid || (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) && ite.id != row.id) {
              items.push({
                "id": ite.id,
                "sortid": items.length + 1
              });
            }
          });
          that.updateMapResourceSort(items);
          break;
        case "orderUp"://排序上移
          items = [];
          let preItem = {};
          let preSortid = row.sortid;
          try {
            that.config.mapSourceData.forEach((ite, i) => {
              if (ite.id == row.id) {
                throw Error();
              } else {
                if (ite.pid == row.pid|| (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) {
                  preSortid = ite.sortid;
                  preItem = {"id": ite.id, "sortid": row.sortid};
                }
              }
            });
          }catch(err){}
          if (preSortid != row.sortid) {
            items.push(preItem);
            items.push({
              "id": row.id,
              "sortid": preSortid
            });
            that.updateMapResourceSort(items)
          }
          break;
        case "orderDown"://排序下移
          let items = [];
          let nextItem = {};
          let nextSortid = row.sortid;
          let x = 0;
          try {
            that.config.mapSourceData.forEach((ite, i) => {
              if (ite.id == row.id) {
                x = 1;
              } else {
                if (ite.pid == row.pid|| (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) {
                  if (x == 1) {
                    nextSortid = ite.sortid;
                    nextItem = {
                      "id": ite.id,
                      "sortid": row.sortid
                    };
                    throw Error();
                  }
                }
              }
            });
          }catch(err){}
          if (nextSortid != row.sortid) {
            items.push(nextItem);
            items.push({
              "id": row.id,
              "sortid": nextSortid
            });
            that.updateMapResourceSort(items);
          }
          break;
        case "orderToBottom"://排序置底
          items = [];
          that.config.mapSourceData.forEach((ite, i) => {
            if ((ite.pid == row.pid || (!gcf.IsNotNullStr(ite.pid) && !gcf.IsNotNullStr(row.pid))) && ite.id != row.id) {
              items.push({
                "id": ite.id,
                "sortid": items.length + 1
              });
            }
          });
          items.push({
            "id": row.id,
            "sortid": items.length + 1
          });
          that.updateMapResourceSort(items);
          break;
      }
    },
    /**
     * 删除节点
     * @param id 节点id
     * @param name 节点名称
     */
    deleteServiceItem(id, name) {
      let that = this;
      that.dialogConfig.config = {
        title: "删除节点",
        show: true,
        innerHtml: "<span>是否删除节点：" + name + "</span>",
        okBtnText: "删除",
        handleOk: function (form) {
          deleteMapSourceItem(form.id).then((res) => {
            bus.$emit("refreshMapSource");
            that.dialogConfig.config.show = false;
          }).catch(resp => {
            console.log('updateMapSource', resp.status + "," + resp.statusText);
          });
        }
      };
      that.dialogConfig.form = {
        operatetype: "delete",
        id: id
      };
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/defaultDialog.vue'], resolve);
    },
    /**
     * 格式化目录树数据
     * @param parentNodes
     * @param parentId
     * @param catalogData
     * @constructor
     */
    formatCatalogTreeData(parentNodes, parentId, catalogData) {
      let that = this;
      for (let i in catalogData) {
        let nodeItem = catalogData[i];
        //2022年3月21日 LQ 数据库里根目录有的为null，有的为''
        if (nodeItem.pid == parentId || (nodeItem.pid == null && parentId == '')) {

          let name = nodeItem.name;
          let node = that.getCatalogItemData(nodeItem, false);
          that.formatCatalogTreeData(node.children, node.id, catalogData);

          parentNodes.push(node);
        }
      }
    },
    /**
     * 格式化父级节点
     * @param parentNodes
     * @param parentId
     * @param checkedId
     * @param removeId
     * @param treeData
     */
    formatParentNodeTreeData(parentNodes, parentId, checkedId, removeId, treeData) {
      let that = this;
      for (let i in treeData) {
        let treeItem = treeData[i];
        if (treeItem.type == 0) {
          if ((treeItem.pid == parentId || (!IsNotNullStr(treeItem.pid) && !IsNotNullStr(parentId))) && treeItem.id != removeId) {
            let tree = gcf.extend({}, {}, treeItem);
            tree.children = [];
            that.formatParentNodeTreeData(tree.children, treeItem.id, checkedId, removeId, treeItem.children);
            parentNodes.push(tree);
          }
        }
      }
    },
    editMapService(row) {
      let that = this;
      that.dialogConfig.config = {
        title: "编辑服务",
        show: true,
        itemShow: {
          isLabel: false
        },
        okBtnText: "确定",
      };
      that.dialogConfig.dialogComponent = resolve => require(['@/views/resource/dialogEditForm/editMapService.vue'], resolve);
      that.config.mapDataTypeData = [];
      that.formatParentNodeTreeData(that.config.mapDataTypeData, "", row.pid, "", that.config.mapSourceTreeData);
      that.dialogConfig.param = {
        parentCatalogTreeData: that.config.mapDataTypeData,
        prjTypes: that.config.prjTypes,
        serviceTypes: that.config.serviceTypes
      };
      let parentCatalogName = that.getCatalogDirName(that.config.mapDataTypeData, row.pid);
      that.dialogConfig.form = {
        id: row.id,
        operatetype: "updateService",
        parentCatalog: row.pid,
        parentCatalogName: parentCatalogName,
        isLabel: row.islabel == 0 ? false : true,
        name: row.name,
        serviceType: row.servicetypevalue,
        url: row.url,
        zmax: row.zmax,
        zmin: row.zmin,
        isvisible: row.isvisible == 0 ? false : true,
        prjType: row.sys,
      }
    },
    /**
     * 获取目录节点Item数据对象
     * @param layerItem {} 节点数据
     * @param visible bool 是否可见
     * @returns {*}
     */
    getCatalogItemData(layerItem, visible) {
      return gcf.extend({}, {
        "label": layerItem.name,
        "name": layerItem.name,
        "children": []
      }, layerItem);
    },
    /**
     * 根据id获取节点名称
     * @param catalogData
     * @param id
     * @returns {string}
     */
    getCatalogDirName(catalogData, id) {
      let that = this;
      let name = "";
      for (let i in catalogData) {
        let item = catalogData[i];
        if (item.id == id) {
          name = item.name;
          break;
        } else if (item.children.length > 0) {
          name = that.getCatalogDirName(item.children, id);
          if (name != "") {
            break;
          }
        }
      }
      return name;
    },
    load(tree, treeNode, resolve) {
    },
    /**
     * 查询底图资源配置
     * @param param
     */
    queryMapSource(param) {
      let that = this;
      listMapSource(param).then((res) => {
        that.config.mapSourceData = res.data.mapSourceData;
        that.config.mapSourceTreeData = [];
        that.formatCatalogTreeData(that.config.mapSourceTreeData, "", that.config.mapSourceData);
      }).catch(resp => {
        console.log('queryMapSource', resp.status + "," + resp.statusText);
      });
    },
    /**
     * 查询服务类型
     * @param param
     */
    queryServiceType(param) {
      let that = this;
      listDict(param).then((res) => {
        that.config.serviceTypes = [];
        for (let i in res.data.dictValue) {
          let item = res.data.dictValue[i];
          that.config.serviceTypes.push({
            name: item.itemtext,
            value: item.itemvalue
          });
        }
      }).catch(resp => {
        console.log('queryDict', resp.status + "," + resp.statusText);
      });
    },
    queryPrjType(param) {
      let that = this;
      listDict(param).then((res) => {
        that.config.prjTypes = [];
        for (let i in res.data.dictValue) {
          let item = res.data.dictValue[i];
          that.config.prjTypes.push({
            name: item.itemtext,
            value: item.itemvalue
          });
        }
      }).catch(resp => {
        console.log('queryDict', resp.status + "," + resp.statusText);
      });
    },
    setAllExpand(arr, state) {
      let that = this;
      arr.forEach(i => {
        that.$refs.catalogTree.toggleRowExpansion(i, state);
        if (i.children) {
          that.setAllExpand(i.children, state);
        }
      });
    },
    /**
     * 更新排序
     * @param params
     */
    updateMapResourceSort(params) {
      let that = this;
      let paramsStr = JSON.stringify(params);
      sortMapSource(paramsStr).then((res) => {
        that.queryMapSource({});
      }).catch(resp => {
        console.log('updateMapSource', resp.status + "," + resp.statusText);
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.main-table-div {
  ::v-deep .el-button + .el-button {
    margin-left: 0;
  }
}
</style>
